﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ICeFramework.Web.UI
{
    public class SWFUpload : WebControl, INamingContainer
    {
        #region public string UploadUrl
        /// <summary>
        /// Get/Sets the UploadUrl of the SWFUpload
        /// </summary>
        /// <value></value>
        public string UploadUrl
        {
            get
            {
                return (string)ViewState["UploadUrl"] ?? string.Empty;
            }
            set
            {
                ViewState["UploadUrl"] = value;
            }
        }
        #endregion

        #region public int FileSizeLimit
        /// <summary>
        /// Get/Sets the FileSizeLimit of the SWFUpload
        /// </summary>
        /// <value></value>
        public int FileSizeLimit
        {
            get
            {
                return (int?)ViewState["FileSizeLimit"] ?? 4;
            }
            set
            {
                ViewState["FileSizeLimit"] = value;
            }
        }
        #endregion

        #region public int FileUploadLimit
        /// <summary>
        /// Get/Sets the FileUploadLimit of the SWFUpload
        /// </summary>
        /// <value></value>
        public int FileUploadLimit
        {
            get
            {
                return (int?)ViewState["FileUploadLimit"] ?? 0;
            }
            set
            {
                ViewState["FileUploadLimit"] = value;
            }
        }
        #endregion

        #region public string Filter
        /// <summary>
        /// Get/Sets the Filter of the SWFUpload
        /// </summary>
        /// <value></value>
        public string Filter
        {
            get
            {
                return (string)ViewState["Filter"] ?? "All Files (*.*)|*.*";
            }
            set
            {
                ViewState["Filter"] = value;
            }
        }
        #endregion

        #region public string FileQueueErrorHandler
        /// <summary>
        /// Get/Sets the FileQueueErrorHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string FileQueueErrorHandler
        {
            get
            {
                return (string)ViewState["FileQueueErrorHandler"] ?? "fileQueueError";
            }
            set
            {
                ViewState["FileQueueErrorHandler"] = value;
            }
        }
        #endregion

        #region public string FileDialogCompleteHandler
        /// <summary>
        /// Get/Sets the FileDialogCompleteHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string FileDialogCompleteHandler
        {
            get
            {
                return (string)ViewState["FileDialogCompleteHandler"] ?? "fileDialogComplete";
            }
            set
            {
                ViewState["FileDialogCompleteHandler"] = value;
            }
        }
        #endregion

        #region public string UploadProgressHandler
        /// <summary>
        /// Get/Sets the UploadProgressHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string UploadProgressHandler
        {
            get
            {
                return (string)ViewState["UploadProgressHandler"] ?? "uploadProgress";
            }
            set
            {
                ViewState["UploadProgressHandler"] = value;
            }
        }
        #endregion

        #region public string UploadErrorHandler
        /// <summary>
        /// Get/Sets the UploadErrorHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string UploadErrorHandler
        {
            get
            {
                return (string)ViewState["UploadErrorHandler"] ?? "uploadError";
            }
            set
            {
                ViewState["UploadErrorHandler"] = value;
            }
        }
        #endregion

        #region public string UploadSuccessHandler
        /// <summary>
        /// Get/Sets the UploadSuccessHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string UploadSuccessHandler
        {
            get
            {
                return (string)ViewState["UploadSuccessHandler"] ?? "uploadSuccess";
            }
            set
            {
                ViewState["UploadSuccessHandler"] = value;
            }
        }
        #endregion

        #region public string UploadCompleteHandler
        /// <summary>
        /// Get/Sets the UploadCompleteHandler of the SWFUpload
        /// </summary>
        /// <value></value>
        public string UploadCompleteHandler
        {
            get
            {
                return (string)ViewState["UploadCompleteHandler"] ?? "uploadComplete";
            }
            set
            {
                ViewState["UploadCompleteHandler"] = value;
            }
        }
        #endregion

        #region public string ButtonImageUrl
        /// <summary>
        /// Get/Sets the ButtonImageUrl of the SWFUpload
        /// </summary>
        /// <value></value>
        public string ButtonImageUrl
        {
            get
            {
                return (string)ViewState["ButtonImageUrl"] ?? "";
            }
            set
            {
                ViewState["ButtonImageUrl"] = value;
            }
        }
        #endregion

        #region public string ButtonPlaceHolderID
        /// <summary>
        /// Get/Sets the ButtonPlaceHolderID of the SWFUpload
        /// </summary>
        /// <value></value>
        public string ButtonPlaceHolderID
        {
            get
            {
                return (string)ViewState["ButtonPlaceHolderID"] ?? "";
            }
            set
            {
                ViewState["ButtonPlaceHolderID"] = value;
            }
        }
        #endregion

        #region public int ButtonWidth
        /// <summary>
        /// Get/Sets the ButtonWidth of the SWFUpload
        /// </summary>
        /// <value></value>
        public int ButtonWidth
        {
            get
            {
                return (int?)ViewState["ButtonWidth"] ?? 160;
            }
            set
            {
                ViewState["ButtonWidth"] = value;
            }
        }
        #endregion

        #region public int ButtonHeight
        /// <summary>
        /// Get/Sets the ButtonHeight of the SWFUpload
        /// </summary>
        /// <value></value>
        public int ButtonHeight
        {
            get
            {
                return (int?)ViewState["ButtonHeight"] ?? 22;
            }
            set
            {
                ViewState["ButtonHeight"] = value;
            }
        }
        #endregion

        #region public string ButtonText
        /// <summary>
        /// Get/Sets the ButtonText of the SWFUpload
        /// </summary>
        /// <value></value>
        public string ButtonText
        {
            get
            {
                return (string)ViewState["ButtonText"] ?? "Select a File";
            }
            set
            {
                ViewState["ButtonText"] = value;
            }
        }
        #endregion

        #region public Style ButtonTextStyle
        /// <summary>
        /// Get/Sets the ButtonTextStyle of the SWFUpload
        /// </summary>
        /// <value></value>
        public string ButtonTextCssClass
        {
            get
            {
                return (string)ViewState["ButtonTextCssClass"];
            }
            set
            {
                ViewState["ButtonTextCssClass"] = value;
            }
        }
        #endregion

        #region public bool Debug
        /// <summary>
        /// Get/Sets the Debug of the SWFUpload
        /// </summary>
        /// <value></value>
        public bool Debug
        {
            get
            {
                return (bool?)ViewState["Debug"] ?? false;
            }
            set
            {
                ViewState["Debug"] = value;
            }
        }
        #endregion

        public string UploadTargetID
        {
            get
            {
                return (string)ViewState["UploadTargetID"] ?? "";
            }
            set
            {
                ViewState["UploadTargetID"] = value;
            }
        }

        public SWFUpload()
        {

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            RegisterScripts();
        }

        private void RegisterScripts()
        {
            Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ICeFramework.Web.UI.Resources.Utils.utils.js");
            Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ICeFramework.Web.UI.Resources.SWFUpload.handlers.js");
            Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ICeFramework.Web.UI.Resources.SWFUpload.swfupload.js");
            if (!Page.ClientScript.IsStartupScriptRegistered("swfUploadInit"))
            {
                string script = GetJSUploadConstructor();
                Page.ClientScript.RegisterStartupScript(this.GetType(), "swfUploadInit", script, true);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        private string GetJSUploadConstructor()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("var swfu;");
            sb.AppendLine("addLoadEvent(swfUploadInit);");
            sb.AppendLine("function swfUploadInit() {");
            sb.AppendLine("\tswfu = new SWFUpload({");
            sb.AppendLine(string.Format("\t\tupload_url: '{0}', ", UploadUrl));
            sb.AppendLine("\t\tpost_params: { 'ASPSESSID': '<%=Session.SessionID %>' },");
            sb.AppendLine();
            sb.AppendLine(string.Format("\t\tfile_size_limit: '{0} MB',", FileSizeLimit));

            string[] filter = ParseFilter();
            sb.AppendLine(string.Format("\t\tfile_types: '{0}',", filter[1]));
            sb.AppendLine(string.Format("\t\tfile_types_description: '{0}',", filter[0]));
            sb.AppendLine(string.Format("\t\tfile_upload_limit: '{0}',    // Zero means unlimited", FileUploadLimit));
            sb.AppendLine(string.Format("\t\tfile_queue_error_handler: {0},", FileQueueErrorHandler));
            sb.AppendLine(string.Format("\t\tfile_dialog_complete_handler: {0},", FileDialogCompleteHandler));
            sb.AppendLine();
            sb.AppendLine(string.Format("\t\tupload_progress_handler: {0},", UploadProgressHandler));
            sb.AppendLine(string.Format("\t\tupload_error_handler: {0},", UploadErrorHandler));
            sb.AppendLine(string.Format("\t\tupload_success_handler: {0},", UploadSuccessHandler));
            sb.AppendLine(string.Format("\t\tupload_complete_handler: {0},", UploadCompleteHandler));
            sb.AppendLine();
            sb.AppendLine(string.Format("\t\tbutton_image_url: '{0}',", ButtonImageUrl));
            sb.AppendLine(string.Format("\t\tbutton_placeholder_id: '{0}',", ButtonPlaceHolderID));
            sb.AppendLine(string.Format("\t\tbutton_width: {0},", ButtonWidth));
            sb.AppendLine(string.Format("\t\tbutton_height: {0},", ButtonHeight));
            sb.AppendLine(string.Format("\t\tbutton_text: '{0}',", ButtonText));
            sb.AppendLine(string.Format("\t\tbutton_text_style: '{0}',", ButtonTextCssClass));
            sb.AppendLine(string.Format("\t\tbutton_text_top_padding: 1,"));
            sb.AppendLine(string.Format("\t\tbutton_text_left_padding: 5,"));
            sb.AppendLine();
            sb.AppendLine(string.Format("\t\tflash_url: '{0}', // Relative to this file", Page.ClientScript.GetWebResourceUrl(this.GetType(), "ICeFramework.Web.UI.Resources.SWFUpload.swfupload.swf")));
            sb.AppendLine(string.Format("\t\tcustom_settings: {{ upload_target: '{0}' }},", UploadTargetID));
            sb.AppendLine();
            sb.AppendLine(string.Format("\t\tdebug: {0}", Debug.ToString().ToLower()));
            sb.AppendLine("\t});");
            sb.AppendLine("}");

            return sb.ToString();
        }

        private string[] ParseFilter()
        {
            //TODO Add multi filter scenario
            string[] sRet = Filter.Split('|');
            if (sRet.Length < 2)
            {
                throw new ArgumentException("Could not parse filter !");
            }
            if (sRet[1].Contains('.'))
            {
                sRet[1] = sRet[1].Substring(sRet[1].IndexOf('.') + 1);
            }
            return sRet;
        }
    }
}

